<template>
  <div class="vditor-preview-container">
    <div ref="previewRef" class="vditor-preview" />
  </div>
</template>
<script setup lang="ts">
  import { ref, onMounted, watch } from 'vue';
  import VditorPreview from 'vditor/dist/method.min';

  /**
   * Markdown预览组件
   * @component
   */
  const props = defineProps({
    /**
     * Markdown内容
     */
    content: {
      type: String,
      required: true,
    },
    /**
     * 预览选项
     */
    options: {
      type: Object,
      default: () => ({}),
    },
  });

  /**
   * 预览容器引用
   */
  const previewRef = ref<HTMLDivElement | null>(null);

  /**
   * 默认预览配置
   */
  const defaultOptions = {
    // cdn: 'https://ld246.com/js/lib/vditor',
    mode: 'light',
    anchor: 1,
    hljs: {
      lineNumber: true,
      style: 'github',
    },
    math: {
      inlineDigit: true,
      macros: {},
    },
    theme: {
      current: 'light',
    },
    lazyLoadImage: '//unpkg.com/vditor/dist/images/img-loading.svg',
  };

  /**
   * 合并配置项
   */
  const mergedOptions = {
    ...defaultOptions,
    ...props.options,
  };

  /**
   * 渲染Markdown内容
   */
  const renderMarkdown = () => {
    if (previewRef.value) {
      VditorPreview.preview(previewRef.value, props.content, mergedOptions);
    }
  };

  /**
   * 组件挂载完成后渲染Markdown
   */
  onMounted(() => {
    renderMarkdown();

    // 渲染其他特殊语法
    VditorPreview.mermaidRender(document);
    VditorPreview.codeRender(document);
    VditorPreview.mathRender(document);
    VditorPreview.abcRender(document);
    VditorPreview.chartRender(document);
    VditorPreview.mindmapRender(document);
    VditorPreview.graphvizRender(document);
  });

  /**
   * 监听内容变化重新渲染
   */
  watch(
    () => props.content,
    () => {
      renderMarkdown();
    },
  );
</script>

<style scoped>
  .vditor-preview-container {
    width: 100%;
  }

  .vditor-preview {
    box-sizing: border-box;
    padding: 16px;
    font-size: 14px;
    /* dark */
    /* color: #ccc;
    background-color: #1a1a1a; */
    /* light */
    /* color: #333;
    background-color: #fff; */
    border-radius: 8px;
  }

  :deep(.vditor-reset) {
    /* background: #1a1a1a; */
    /* background: #fff; */
  }

  :deep(.vditor-reset h1),
  :deep(.vditor-reset h2),
  :deep(.vditor-reset h3),
  :deep(.vditor-reset h4),
  :deep(.vditor-reset h5),
  :deep(.vditor-reset h6) {
    /* color: #06ad7e; */
    /* margin-top: 1.5em; */
    /* margin-bottom: 0.5em; */
    /* font-weight: 600; */
    /* border-bottom: none; */
  }

  :deep(.vditor-reset h3) {
    padding-bottom: 0.3em;
    font-size: 1.3em;
  }

  :deep(.vditor-reset strong) {
    font-weight: 600;
    color: #fff;
  }
</style>
